import 'package:flutter/material.dart';
import 'package:flutter_frame/common/app_config.dart';
import 'package:flutter_frame/common/router.dart';
import 'package:flutter_frame/common/user_manager.dart';
import 'package:flutter_frame/http/http.dart';
import 'package:flutter_frame/page/login/bean/user_model.dart';
import 'package:flutter_frame/utils/toast_utils.dart';
import 'package:flutter_frame/utils/utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../assets/color_config.dart';
import '../../common/common_config.dart';
import '../../utils/theme_util.dart';
import '../../weiget/image_widget.dart';
import '../../weiget/imgcode_dialog.dart';
import '../../weiget/over_scroll_behavior.dart';
import 'bean/region_model.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginPageState();
}

class LoginPageState extends State {
  var count = 1.obs;
  TextEditingController mobileController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  Rx<RegionModel> regionModel = RegionModel.fromJson({
    "coutryName": "中国",
    "countryCode": "+86",
    "icon": "icon_zh",
    "remark": "中国",
  }).obs;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorConfig.colorWhite,
      appBar: AppBar(
        toolbarHeight: 0,
        elevation: 0,
        backgroundColor: Colors.transparent,
        foregroundColor: Colors.transparent,
        systemOverlayStyle: ThemeUtil.systemOverlayStyleLight,
      ),
      extendBodyBehindAppBar: true,
      body: ScrollConfiguration(
        behavior: OverScrollBehavior(),
        child: SingleChildScrollView(
          physics: const ClampingScrollPhysics(),
          child: SizedBox(
            width: double.infinity,
            height: MediaQuery.of(context).size.height,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  height: 200.h,
                  child: Text('Cloud Pick',
                      style: TextStyle(
                          color: ColorConfig.colorBlack,
                          fontSize: 40.sp,
                          fontWeight: FontWeight.bold)),
                ),
                Card(
                  shadowColor: ColorConfig.colorBlack,
                  elevation: 4.w,
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Column(
                    children: [
                      //手机号码
                      Container(
                        margin:
                            EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
                        padding: EdgeInsets.only(left: 10.w),
                        width: double.infinity,
                        height: 45.w,
                        decoration: BoxDecoration(
                            color: ColorConfig.colorF5,
                            borderRadius: BorderRadius.circular(10.w)),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            //国旗
                            GestureDetector(
                                onTap: () => {getRegion()},
                                child: Obx(() => Row(
                                      children: [
                                        ImageWidget(
                                          name:
                                              "${assetImage}country/${regionModel.value.icon}.png",
                                          width: 30.w,
                                          fit: BoxFit.fitWidth,
                                        ),
                                        Container(
                                          margin: EdgeInsets.symmetric(
                                              horizontal: 6.w),
                                          child: Text(
                                            regionModel.value.countryCode,
                                            style: TextStyle(
                                                color: ColorConfig.colorBlack,
                                                fontSize: 14.sp),
                                          ),
                                        )
                                      ],
                                    ))),
                            //手机号
                            Expanded(
                              child: Container(
                                child: TextField(
                                  decoration: InputDecoration(
                                      counterText: '',
                                      hintText: '请输入手机号',
                                      border: InputBorder.none),
                                  controller: mobileController,
                                  maxLines: 1,
                                  keyboardType: TextInputType.phone,
                                  style: TextStyle(
                                      color: ColorConfig.colorBlack,
                                      fontSize: 12.sp),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      //验证码
                      Container(
                        height: 45.w,
                        margin:
                            EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            //输入验证码
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10.w),
                                decoration: BoxDecoration(
                                    color: ColorConfig.colorF5,
                                    borderRadius: BorderRadius.circular(10.w)),
                                child: TextField(
                                  controller: codeController,
                                  decoration: InputDecoration(
                                      counterText: '',
                                      hintText: '请输入验证码',
                                      border: InputBorder.none),
                                  maxLength: 6,
                                  maxLines: 1,
                                  keyboardType: TextInputType.number,
                                  style: TextStyle(
                                    color: ColorConfig.colorBlack,
                                    fontSize: 12.sp,
                                  ),
                                ),
                              ),
                            ),

                            //获取验证码按钮
                            GestureDetector(
                              onTap: () => {getSmsCode()},
                              child: Container(
                                margin: EdgeInsets.only(left: 10.w),
                                height: 45.h,
                                padding: EdgeInsets.symmetric(horizontal: 10.w),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: ColorConfig.colorBlack,
                                    borderRadius: BorderRadius.circular(10.w)),
                                child: Text(
                                  '获取验证码',
                                  style: TextStyle(
                                      color: ColorConfig.colorWhite,
                                      fontSize: 14.sp),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      //登录按钮
                      GestureDetector(
                        onTap: () => {login()},
                        child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: ColorConfig.colorBlack,
                              borderRadius: BorderRadius.circular(10.w)),
                          width: double.infinity,
                          height: 45.h,
                          margin: EdgeInsets.symmetric(
                              vertical: 20.h, horizontal: 20.w),
                          child: Text(
                            '登录',
                            style: TextStyle(
                                color: ColorConfig.colorWhite, fontSize: 14.sp),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(
                    child: Container(
                  margin: EdgeInsets.only(bottom: 20.w),
                  alignment: Alignment.bottomCenter,
                  child: Text(
                    'v 1.0.0',
                    style: TextStyle(color: ColorConfig.colorBlack),
                  ),
                ))
              ],
            ),
          ),
        ),
      ),
    );
  }

  //登录
  login() {
    var mobile = mobileController.text;
    var code = codeController.text;
    var region = regionModel.value.countryCode;
    var params = {
      "mobile": mobile,
      "smsCode": code,
      "region": region,
      "channel": AppConfig().getChannel(),
    };
    Http().post(apiLoginUrl, loading: true, body: params, success: (bean) {
      bean.data["mobile"] = mobile;
      var userModel = UserModel.fromJson(bean.data);
      UserManager().saveData(userModel);
      Get.toNamed(Routers.tabBar);
    });
  }

  //获取国家区号
  getRegion() async {
    regionModel.value = await Get.toNamed(Routers.region);
  }

  //获取验证码
  getSmsCode({String? imageCaptcha = ""}) {
    var mobile = mobileController.text;
    Map params = {
      "mobile": mobile,
      "captchaValue": imageCaptcha ?? "",
      "region": regionModel.value.countryCode,
      "channel": AppConfig().getChannel(),
    };
    Http().post(apiSendSmsUrl, body: params, success: (bean) {
      showToast("send_sms_success".tr);
    }, error: (bean) {
      if (bean.code == "LGN3001003") {
        //需要图形验证码的情况
        String captchaUrl = bean.data["captchaUrl"];
        showImgCodeAlertView(captchaUrl, mobile);
      } else if (bean.code == "LGN3001004") {
        //图片验证码验证错误
        showToast("message_image_captcha_error".tr);
        reloadImageCaptcha(mobile);
      } else {
        showToast(bean.message);
      }
    });
  }

  ///显示图形验证码
  void showImgCodeAlertView(String imgUrl, String mobile) {
    var dialog = ImgCodeDialog(
      imgUrl: imgUrl,
      mobile: mobile,
      region: regionModel.value.countryCode,
      focusNode: FocusNode(),
      onChanged: (String value) {
        //重新验证验证码
        getSmsCode(imageCaptcha: value);
      },
    );
    showDialog<bool>(
      context: context,
      barrierDismissible: false,
      barrierColor: Colors.transparent,
      useSafeArea: false,
      builder: (context) {
        return GestureDetector(
          onTap: () async {
            if (dialog.focusNode?.hasFocus == true) {
              Utils.hideTextInput();
              dialog.focusNode?.unfocus();
              return;
            }
            Get.back();
          },
          child: Container(
            color: Colors.black54,
            width: Get.width,
            height: Get.height,
            child: Center(
              child: dialog,
            ),
          ),
        );
      },
    );
  }

  ///重新刷新图形验证码
  void reloadImageCaptcha(String mobile) {
    Map params = {"mobile": mobile, "region": regionModel.value.countryCode};
    Http().post(apiGetCaptUrl, body: params, loading: true, success: (res) {
      String captchaUrl = res.data["captchaUrl"];
      showImgCodeAlertView(captchaUrl, mobile);
    });
  }
}
